import scrapy
from dangdangwang.items import DangdangwangItem


class DangdangspiderSpider(scrapy.Spider):
    name = "dangdangspider"
    allowed_domains = ["category.dangdang.com"]
    start_urls = ["https://category.dangdang.com/cp01.01.02.00.00.00.html"]

    base_url = "http://category.dangdang.com/pg"
    page = 1

    def parse(self, response):
        print(
            "\n\n==============================================================================\n\n"
        )

        # src =//ul[@id="component_59"]/li//img/@src
        # alt = //ul[@id="component 59"]/li//img/@alt
        # price = //ul[@id="component_59"]/li//p[@class="price"]/span[1]/text()
        # 所有的selector的对象都可以再次调用xpath方法
        li_list = response.xpath("//ul[@id='component_59']/li")
        for li in li_list:
            src = li.xpath(".//img/@data-original").extract_first()
            if src:
                src = src
            else:
                src = li.xpath(".//img/@src").extract_first()
            name = li.xpath(".//img/@alt").extract_first()
            price = li.xpath(".//p[@class='price']/span[1]/text()").extract_first()
            print(src, name, price)

            book = DangdangwangItem(src=src, name=name, price=price)

            # 获取一个book就将book交给pipelines
            yield book

        if self.page < 100:
            self.page = self.page + 1
            result_url = self.base_url + str(self.page) + "-cp01.01.02.00.00.00.html"
            yield scrapy.Request(url=result_url, callback=self.parse)
